from app.models.order import Order
from app.models.order_item import OrderItem
from app.models.product import Product
from app import db

class OrderService:
    def get_user_orders(self, user_id):
        orders = Order.query.filter_by(user_id=user_id).all()
        return [self._format_order(order) for order in orders]
    
    def get_order_by_id(self, order_id, user_id):
        order = Order.query.filter_by(id=order_id, user_id=user_id).first_or_404()
        return self._format_order(order)
    
    def create_order(self, user_id, data):
        total_amount = 0
        order_items = []
        
        for item in data['items']:
            product = Product.query.get_or_404(item['product_id'])
            if product.stock < item['quantity']:
                return {'error': f'商品 {product.name} 库存不足'}, 400
            
            total_amount += product.price * item['quantity']
            order_items.append(OrderItem(
                product_id=product.id,
                quantity=item['quantity'],
                price=product.price
            ))
            
            product.stock -= item['quantity']
        
        order = Order(
            user_id=user_id,
            total_amount=total_amount,
            status='pending'
        )
        
        db.session.add(order)
        db.session.flush()  # 获取order.id
        
        for item in order_items:
            item.order_id = order.id
            db.session.add(item)
        
        db.session.commit()
        
        return self._format_order(order)
    
    def update_order(self, order_id, user_id, data):
        order = Order.query.filter_by(id=order_id, user_id=user_id).first_or_404()
        
        if 'status' in data:
            order.status = data['status']
        
        db.session.commit()
        
        return self._format_order(order)
    
    def _format_order(self, order):
        return {
            'id': order.id,
            'user_id': order.user_id,
            'total_amount': order.total_amount,
            'status': order.status,
            'created_at': order.created_at.isoformat(),
            'items': [{
                'id': item.id,
                'product_id': item.product_id,
                'quantity': item.quantity,
                'price': item.price
            } for item in order.items]
        } 